<template>
  <div class="volunteer-home">
    <!-- 顶部用户信息栏 -->
    <div class="user-header" v-if="!loading && userInfo && volunteerInfo">
      <div class="user-profile">
        <el-avatar :size="60" :src="userInfo.avatarUrl || defaultAvatar" />
        <div class="user-details">
          <div class="username">{{ userInfo.username || '未登录用户' }}</div>
          <div class="user-stats">
            <div class="stat-item">
              <span>服务时长</span>
              <span class="value">{{ volunteerInfo.totalServiceHours || 0 }}h</span>
            </div>
            <div class="stat-item">
              <span>活动积分</span>
              <span class="value">{{ currentPoints || 0 }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态提示 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>加载中...</span>
    </div>

    <!-- 主内容区 -->
    <div v-if="!loading" class="main-content">
      <!-- 左侧菜单-->
      <div class="left-menu">
        <!-- 个人信息 -->
        <div class="menu-section" style="background-color: #eeeeee;">
          <div class="menu-title">个人信息</div>
          <div class="menu-items">
            <div
                class="menu-item"
                :class="{ 'active': activeMenu === 'account-security' }"
                @click="handleMenuSelect('account-security')"
            >
              <el-icon><User /></el-icon> 账号安全
            </div>
            <div
                class="menu-item"
                :class="{ 'active': activeMenu === 'basic-info' }"
                @click="handleMenuSelect('basic-info')"
            >
              <el-icon><InfoFilled /></el-icon> 基本信息
            </div>
            <div
                class="menu-item"
                :class="{ 'active': activeMenu === 'notifications' }"
                @click="handleMenuSelect('notifications')"
            >
              <el-icon><Bell /></el-icon> 通知
            </div>
          </div>
        </div>

        <!-- 公益活动 -->
        <div class="menu-section" style="background-color: #eeeeee;">
          <div class="menu-title">公益活动</div>
          <div class="menu-items">
            <div
                class="menu-item"
                :class="{ 'active': activeMenu === 'activity-list' }"
                @click="handleMenuSelect('activity-list')"
            >
              <el-icon><List /></el-icon> 活动列表
            </div>
            <div
                class="menu-item"
                :class="{ 'active': activeMenu === 'my-activities' }"
                @click="handleMenuSelect('my-activities')"
            >
              <el-icon><Calendar /></el-icon> 我的活动
            </div>
          </div>
        </div>

        <!-- 兑换中心 -->
        <div class="menu-section" style="background-color: #eeeeee;">
          <div class="menu-title">兑换中心</div>
          <div class="menu-items">
            <div
                class="menu-item"
                :class="{ 'active': activeMenu === 'points-goods' }"
                @click="handleMenuSelect('points-goods')"
            >
              <el-icon><Goods /></el-icon> 商品列表
            </div>
            <div
                class="menu-item"
                :class="{ 'active': activeMenu === 'my-points-exchanges' }"
                @click="handleMenuSelect('my-points-exchanges')"
            >
              <el-icon><Document /></el-icon> 兑换记录
            </div>
          </div>
        </div>

        <!-- 其他 -->
        <div class="menu-section" style="background-color:#eeeeee;">
          <div class="menu-title">其他</div>
          <div class="menu-items">
            <div
                class="menu-item"
                :class="{ 'active': activeMenu === 'service' }"
                @click="showServiceDialog"
            >
              <el-icon><Service /></el-icon> 服务
            </div>
            <div
                class="menu-item"
                :class="{ 'active': activeMenu === 'report' }"
                @click="showReportDialog"
            >
              <el-icon><Warning /></el-icon> 举报
            </div>
            <div
                class="menu-item"
                :class="{ 'active': activeMenu === 'agreement' }"
                @click="showAgreementDialog"
            >
              <el-icon><DocumentCopy /></el-icon> 协议
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧轮播图卡片-->
      <div class="right-card">
        <div class="card-title">年度志愿者风采</div>
        <el-carousel height="100%" :interval="3000" arrow="always">
          <el-carousel-item v-for="(item, index) in carouselItems" :key="index">
            <img :src="item.image" class="carousel-image" :alt="'志愿者风采' + (index + 1)" />
            <div class="carousel-caption">{{ item.title }}</div>
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>

    <!-- 服务对话框 -->
    <el-dialog
        v-model="serviceDialogVisible"
        title="志愿者服务咨询"
        width="500px"
        class="service-dialog"
    >
      <div class="service-content">
        <div class="service-header">
          <el-avatar :size="40" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
          <span class="service-title">志愿者服务-官方</span>
        </div>

        <div class="service-message">
          <p>您好，关于志愿者服务相关问题，请查看以下常见问题解答。如果仍有疑问，可以在下方输入您的问题。</p>
        </div>

        <div class="common-questions">
          <h4>最近大家都在问：</h4>
          <ul>
            <li
                v-for="(question, index) in commonQuestions"
                :key="index"
                @click="selectQuestion(question)"
            >
              {{ question.text }}
            </li>
          </ul>
        </div>

        <div class="quick-links">
          <el-button
              v-for="(link, index) in quickLinks"
              :key="index"
              size="small"
              @click="selectQuickLink(link)"
          >
            {{ link.text }}
          </el-button>
        </div>

        <div class="input-area">
          <el-input
              v-model="userQuestion"
              placeholder="请输入想要咨询的问题"
              clearable
              @keyup.enter="sendQuestion"
          >
            <template #append>
              <el-button @click="sendQuestion">
                <el-icon><Promotion /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </el-dialog>

    <!-- 举报对话框 -->
    <el-dialog
        v-model="reportDialogVisible"
        title="投诉举报"
        width="50%"
    >
      <div class="report-content">
        <h3>投诉色情有害信息</h3>
        <h4>投诉涉未成年人有害信息</h4>
        <h4>投诉数据造假信息</h4>

        <p><strong>涉算法专项举报：</strong></p>
        <p>help@jjwxc.com/4008705552</p>

        <p><strong>涉养老诈骗专项举报：</strong></p>
        <p>help@jjwxc.com/4008705552</p>

        <p><strong>涉网络暴力专项举报：</strong></p>
        <p>help@jjwxc.com/4008705552</p>

        <p><strong>网上有害信息举报专区：</strong></p>
        <p>https://www.12377.cn/</p>

        <p><strong>公安部网络违法犯罪举报网站：</strong></p>
        <p>http://cyberpolice.mps.gov.cn/wfjb/</p>

        <p>为强化举报指引，优化投诉举报受理处置流程，我们在设置了相应的专项便捷举报渠道的基础上，特别设置了App举报投诉入口，汇总各类举报投诉方法，进一步方便用户对违法违规信息进行举报。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reportDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 协议对话框 -->
    <el-dialog
        v-model="agreementDialogVisible"
        title="志愿者服务协议"
        width="60%"
        class="agreement-dialog"
    >
      <div class="agreement-content">
        <h3>志愿者服务协议</h3>

        <div class="agreement-section">
          <h4>第一章 总则</h4>
          <p>第一条 为规范志愿者服务行为，保障志愿者和志愿服务对象的合法权益，促进志愿服务事业发展，制定本协议。</p>
          <p>第二条 本协议适用于在本平台注册并参与志愿服务活动的志愿者。</p>
        </div>

        <div class="agreement-section">
          <h4>第二章 志愿者权利与义务</h4>
          <p>第三条 志愿者享有以下权利：</p>
          <ul>
            <li>1. 自愿加入或退出志愿服务组织；</li>
            <li>2. 获得志愿服务活动真实、准确、完整的信息；</li>
            <li>3. 获得志愿服务活动必要的条件和保障；</li>
            <li>4. 获得志愿服务活动相关的培训和指导；</li>
            <li>5. 对志愿服务工作提出意见和建议。</li>
          </ul>

          <p>第四条 志愿者应当履行以下义务：</p>
          <ul>
            <li>1. 遵守国家法律法规和志愿服务组织的规章制度；</li>
            <li>2. 履行志愿服务承诺，按时完成志愿服务工作；</li>
            <li>3. 保守志愿服务对象的个人隐私和商业秘密；</li>
            <li>4. 不得向志愿服务对象收取或者变相收取报酬；</li>
            <li>5. 维护志愿服务组织和志愿者的形象和声誉。</li>
          </ul>
        </div>

        <div class="agreement-section">
          <h4>第三章 服务时长与积分</h4>
          <p>第五条 志愿者参与志愿服务活动可获得相应服务时长记录。</p>
          <p>第六条 服务时长是志愿者参与志愿服务的重要依据，可用于：</p>
          <ul>
            <li>1. 志愿者星级评定；</li>
            <li>2. 优秀志愿者评选；</li>
            <li>3. 积分兑换等。</li>
          </ul>
          <p>第七条 积分可用于兑换平台提供的相应商品或服务，积分规则由平台另行制定。</p>
        </div>

        <div class="agreement-section">
          <h4>第四章 免责声明</h4>
          <p>第八条 志愿者在服务过程中应自行承担人身和财产安全责任。</p>
          <p>第九条 平台仅为志愿服务提供信息发布和对接服务，不承担志愿者与服务对象之间的纠纷责任。</p>
        </div>

        <div class="agreement-section">
          <h4>第五章 附则</h4>
          <p>第十条 本协议自志愿者注册之日起生效。</p>
          <p>第十一条 平台有权根据实际情况修改本协议，修改后的协议将在平台公示后生效。</p>
          <p>第十二条 本协议最终解释权归平台所有。</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="agreeAgreement">同意协议</el-button>
          <el-button @click="agreementDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  ElMessage, ElCarousel, ElCarouselItem, ElDialog, ElButton, ElInput, ElAvatar
} from 'element-plus'
import {
  Loading, User, InfoFilled, Bell, List, Calendar, Goods, Document,
  Service, Warning, DocumentCopy, Promotion
} from '@element-plus/icons-vue'
import axios from 'axios'
import qs from 'qs'

const router = useRouter()
const route = useRoute()

// 默认头像URL
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 轮播图数据
const carouselItems = ref([
  {
    image: '/images/volunteer1.png',
    title: '社区服务优秀志愿者'
  },
  {
    image:'/images/volunteer2.png' ,
    title: '环保活动先进个人'
  },
  {
    image: '/images/volunteer3.png',
    title: '年度志愿服务之星'
  },
  {
    image: '/images/volunteer4.png',
    title: '敬老院服务标兵'
  }
])

// 状态变量
const activeMenu = ref('account-security')
const loading = ref(true)
const userInfo = ref({
  avatarUrl: '',
  username: ''
})
const volunteerInfo = ref({
  totalServiceHours: 0
})
const currentPoints = ref(0)
const reportDialogVisible = ref(false)
const serviceDialogVisible = ref(false) // 只保留这一处声明
const agreementDialogVisible = ref(false)
const userQuestion = ref('')
const commonQuestions = ref([
  { text: '如何报名参加志愿活动？', answer: '您可以在"活动列表"中浏览所有活动，点击感兴趣的活动查看详情并报名。' },
  { text: '如何查询我的服务时长？', answer: '您的总服务时长显示在个人主页顶部，详细记录可在"我的活动"中查看。' },
  { text: '活动积分如何使用？', answer: '积分可以在"兑换中心"兑换商品或服务，具体可在商品列表查看。' },
  { text: '如何修改个人信息？', answer: '您可以在"基本信息"页面修改您的个人信息。' },
  { text: '活动当天无法参加怎么办？', answer: '请在活动开始前24小时在"我的活动"中取消报名，否则可能会影响您的信用。' },
  { text: '如何成为志愿者？', answer: '注册账号并通过基本信息审核后，您就可以成为我们的志愿者了。' }
])
const quickLinks = ref([
  { text: '我是志愿者', answer: '志愿者相关问题解答' },
  { text: '活动报名', answer: '活动报名流程说明' },
  { text: '积分问题', answer: '积分获取和使用规则' },
  { text: '联系客服', answer: '如需人工帮助，请拨打客服电话: 400-123-4567' }
])
const currentAnswer = ref('')

// 加载用户数据
const loadUserData = async () => {
  try {
    const userStr = localStorage.getItem('user');
    if (!userStr) {
      throw new Error('未获取到用户信息');
    }

    const userData = JSON.parse(userStr);
    const username = userData.user.username;

    console.log('当前用户:', username);

    const [userRes, volunteerRes] = await Promise.all([
      axios.get(BASE_URL + '/api/volunteer/userInfo', {
        params: {username},
        paramsSerializer: params => qs.stringify(params)
      }),
      axios.get(BASE_URL + '/api/volunteer/volunteerInfo', {
        params: {username},
        paramsSerializer: params => qs.stringify(params)
      })
    ]);

    console.log('用户信息响应:', userRes.data); // 添加调试信息
    console.log('志愿者信息响应:', volunteerRes.data); // 添加调试信息

    userInfo.value = {
      avatarUrl: userRes.data?.data?.avatarUrl || defaultAvatar,
      username: userRes.data?.data?.username || '未知用户',
      ...userRes.data?.data
    };

    volunteerInfo.value = {
      totalServiceHours: volunteerRes.data?.data?.totalServiceHours || 0,
      ...volunteerRes.data?.data
    }

    currentPoints.value = volunteerInfo.value.totalPoints || 0

  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('加载用户信息失败，请刷新重试')
    userInfo.value = {
      avatarUrl: defaultAvatar,
      username: '未知用户'
    }
    volunteerInfo.value = {
      totalServiceHours: 0
    }
    currentPoints.value = 0
  } finally {
    loading.value = false
  }
}

// 处理菜单选择事件
const handleMenuSelect = (menuKey) => {
  activeMenu.value = menuKey

  const routes = {
    'account-security': '/volunteer/account-security',
    'basic-info': '/volunteer/basic-info',
    'notifications': '/volunteer/notifications',
    'activity-list': '/volunteer/activity-list',
    'my-activities': '/volunteer/my-activities',
    'points-goods': '/volunteer/points-goods',
    'my-points-exchanges': '/volunteer/my-points-exchanges',
    'service': '/volunteer/service',
    'report': '/volunteer/report',
    'agreement': '/volunteer/agreement'
  }

  if (routes[menuKey]) {
    router.push(routes[menuKey])
  } else {
    ElMessage.warning('暂未配置该菜单项的路由')
  }
}

// 显示举报对话框
const showReportDialog = () => {
  reportDialogVisible.value = true
}

// 显示服务对话框
const showServiceDialog = () => {
  serviceDialogVisible.value = true
  currentAnswer.value = ''
}

// 选择问题
const selectQuestion = (question) => {
  currentAnswer.value = question.answer
}

// 选择快速链接
const selectQuickLink = (link) => {
  currentAnswer.value = link.answer
}

// 发送问题
const sendQuestion = () => {
  if (userQuestion.value.trim()) {
    currentAnswer.value = `您的问题 "${userQuestion.value}" 已提交，客服将在24小时内回复您。`
    userQuestion.value = ''
  }
}

// 显示协议对话框
const showAgreementDialog = () => {
  agreementDialogVisible.value = true
}

// 同意协议
const agreeAgreement = () => {
  ElMessage.success('您已同意志愿者服务协议')
  agreementDialogVisible.value = false
}

// 根据当前路径设置初始激活菜单
const initActiveMenu = (path) => {
  const pathMap = {
    '/volunteer/account-security': 'account-security',
    '/volunteer/basic-info': 'basic-info',
    '/volunteer/notifications': 'notifications',
    '/volunteer/activity-list': 'activity-list',
    '/volunteer/my-activities': 'my-activities',
    '/volunteer/points-goods': 'points-goods',
    '/volunteer/my-points-exchanges': 'my-points-exchanges',
    '/volunteer/service': 'service',
    '/volunteer/report': 'report',
    '/volunteer/agreement': 'agreement'
  }
  activeMenu.value = pathMap[path] || 'account-security'
}

onMounted(() => {
  loadUserData()
  initActiveMenu(route.path)
})

// 监听路由变化更新菜单状态
watch(
    () => route.path,
    (newPath) => {
      initActiveMenu(newPath)
    }
)
</script>

<style scoped>
.volunteer-home {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #d9d9d9;
}

.user-header {
  background-color:  #4a80f0;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-details {
  flex: 1;
}

.username {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #fff;
}

.user-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  display: flex;
  flex-direction: column;
}

.stat-item span:first-child {
  font-size: 14px;
  color: #e6f7ff;
}

.stat-item .value {
  font-size: 16px;
  font-weight: 600;
  color: #fff;
  margin-top: 5px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.loading-icon {
  font-size: 24px;
  margin-bottom: 10px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.main-content {
  flex: 1;
  display: flex;
  padding: 20px;
  gap: 20px;
  background-color: #f8f9fa;
  overflow-y: auto;
}

.left-menu {
  flex: 3;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.menu-section {
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  flex: 1;
}

.menu-title {
  font-size: 16px;
  color: #0d5bcf;
  font-weight: 600;
  margin-bottom: 16px;
  padding-left: 8px;
}

.menu-items {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.menu-item {
  padding: 12px 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 20px;
  color: #333;
  border: 1px solid #eaeaea;
  display: flex;
  align-items: center;
  gap: 8px;
}

.menu-item:hover {
  background-color: #eef5ff;
  border-color: #d0e3ff;
  color: #4a80f0;
}

.menu-item.active {
  background-color: #eef5ff;
  border-color: #4a80f0;
  color: #4a80f0;
  font-weight: 600;
}

.right-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  min-height: 0;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  text-align: center;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.carousel-caption {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  text-align: center;
  color: white;
  font-size: 16px;
  font-weight: bold;
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.8);
  padding: 8px;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 0 0 8px 8px;
}

.el-carousel {
  border-radius: 8px;
  overflow: hidden;
  flex: 1;
  min-height: 0;
}

.el-carousel__container {
  height: 100%;
}

/* 服务对话框样式 */
.service-dialog .el-dialog__body {
  padding: 15px 20px;
}

.service-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.service-title {
  margin-left: 10px;
  font-weight: bold;
  font-size: 16px;
}

.service-message {
  background-color: #f5f5f5;
  padding: 10px 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  font-size: 14px;
}

.common-questions {
  margin-bottom: 20px;
}

.common-questions h4 {
  margin-bottom: 10px;
  color: #666;
  font-size: 14px;
}

.common-questions ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.common-questions li {
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
  cursor: pointer;
  color: #1a73e8;
  font-size: 14px;
}

.common-questions li:hover {
  color: #0d5bcf;
}

.quick-links {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.quick-links .el-button {
  background-color: #f5f5f5;
  border-color: #ddd;
  color: #333;
}

.quick-links .el-button:hover {
  background-color: #e9e9e9;
}

.input-area {
  margin-top: 20px;
}

.answer-area {
  margin-top: 15px;
  padding: 10px 15px;
  background-color: #f0f8ff;
  border-radius: 8px;
  border-left: 3px solid #1a73e8;
}

.answer-area p {
  margin: 0;
  font-size: 14px;
  color: #333;
}

/* 举报对话框样式 */
.report-content {
  line-height: 1.6;
}

.report-content h3 {
  margin-top: 0;
  color: #333;
}

.report-content h4 {
  margin: 15px 0 10px;
  color: #555;
}

.report-content p {
  margin: 8px 0;
}

.report-content strong {
  color: #333;
}

/* 协议对话框样式 */
.agreement-dialog .el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
}

.agreement-content {
  line-height: 1.8;
}

.agreement-content h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.agreement-section {
  margin-bottom: 20px;
}

.agreement-section h4 {
  color: #1a73e8;
  margin: 15px 0 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.agreement-section p {
  margin: 10px 0;
  text-indent: 2em;
}

.agreement-section ul {
  margin: 10px 0;
  padding-left: 40px;
}

.agreement-section li {
  margin-bottom: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>